package com.xuqm.sdhbwfu.app.ui

import android.Manifest
import android.content.ComponentName
import android.content.Intent
import android.provider.MediaStore
import androidx.activity.viewModels
import com.bigkoo.alertview.AlertView
import com.xuqm.base.common.FileHelper
import com.xuqm.base.common.TimeHelper
import com.xuqm.base.common.ToolsHelper
import com.xuqm.base.dialog.loading.LoadingDialog
import com.xuqm.base.extensions.runWithPermission
import com.xuqm.base.extensions.showMessage
import com.xuqm.base.ui.BaseActivity
import com.xuqm.sdhbwfu.app.R
import com.xuqm.sdhbwfu.app.data.RiskTodoConfirmData
import com.xuqm.sdhbwfu.app.databinding.ActivityRiskTodoBinding
import com.xuqm.sdhbwfu.app.viewmodel.RiskTodoViewModel
import com.xuqm.sdhbwfu.core.extensions.visible
import java.io.File

class RiskTodoActivity : BaseActivity<ActivityRiskTodoBinding>() {

    override fun getLayoutId(): Int = R.layout.activity_risk_todo
    override fun fullscreen(): Boolean = true

    var workNum: String? = ""
    var taskId: String = ""

    val vm: RiskTodoViewModel by viewModels()

    lateinit var confirmData: RiskTodoConfirmData


    override fun initData() {
        super.initData()
        workNum = intent?.getStringExtra("workNum")
        if (ToolsHelper.isNull(workNum)) {
            "获取数据失败".showMessage()
            return
        }

        if (!this::confirmData.isInitialized) {
            confirmData =
                RiskTodoConfirmData(
                    listOf(),
                    "",
                    0,
                    taskId,
                    workNum!!
                )
        }

        binding.riskTodoConfirmStatusLyt.setOnClickListener {

            AlertView(
                "请选择处理状态",
                null,
                "",
                arrayOf("未处理", "已处理"),
                arrayOf("取消"),
                this,
                AlertView.Style.ActionSheet
            ) { _, pos ->
                if (pos != 2) {
                    binding.riskTodoConfirmStatus.text = when (pos) {
                        0 -> "未处理"
                        else -> "已处理"
                    }
                    confirmData.status = pos
                }
            }.show()
        }
        binding.riskConfirmBtn.setOnClickListener {
            confirmData.remarks = binding.riskTodoConfirmRemarks.text.toString()
            LoadingDialog.showDialog("")
            vm.confirmform(confirmData)
        }
        binding.riskTodoConfirmAttsLyt.setOnClickListener {
            runWithPermission(
                Manifest.permission.CAMERA,
                rationaleMethod = {
                    AlertView(
                        "无法获取摄像头使用权限", "上传附件需要开启相机权限才能使用。",
                        null, arrayOf("确定"), null, mContext,
                        AlertView.Style.Alert
                    ) { _, _ ->
                    }.show()
                },
                permanentDeniedMethod = {
                    "请在设置界面打开摄像头权限".showMessage()
                    AlertView(
                        "无法获取摄像头使用权限", "上传附件需要开启相机权限才能使用，请在应用权限管理页面打开相关权限。",
                        null, arrayOf("确定"), null, mContext,
                        AlertView.Style.Alert
                    ) { _, _ ->
                    }.show()
                },
                callback = {
                    dispatchTakePictureIntent()
                })
        }

        vm.confirmForm.observe(this) {
            LoadingDialog.dismissDialog()
            if (null != it) {
                "处理完成".showMessage()
                finish()
            }
        }
        vm.status.observe(this) {
            LoadingDialog.dismissDialog()
            if (null != it) {
                binding.riskTodoConfirmAtts.text = it.name
                confirmData.annex = listOf(RiskTodoConfirmData.Annex(it.fsId, it.name))
            }
        }
        vm.recordList.observe(this) {
            LoadingDialog.dismissDialog()
            if (!it.isNullOrEmpty()) {
                for (recordModel in it) {
                    if (!recordModel.isCurrent) {
                        when (recordModel.nodeName) {
                            "风险单" -> {
                                binding.riskTodoOrder.visible()
                                vm.applyform(workNum!!, recordModel.taskId)
                            }
                            "风险判断" -> {
                                binding.riskTodoCheck.visible()
                                vm.judgmentform(workNum!!, recordModel.taskId)
                            }
                            "风险处理" -> {
                                binding.riskTodoTodo.visible()
                                binding.riskTodoTodoName.text = "${recordModel.approveUser} 审批"
                                vm.managementform(workNum!!, recordModel.taskId)
                            }
                        }

                    } else {
                        taskId = recordModel.taskId
                        confirmData.taskId = recordModel.taskId
                    }
                }
            }

        }
        vm.applyForm.observe(this) {
            if (null != it) {
                binding.riskTodoTitle.text = it.title
                binding.title.text = it.title
                binding.riskTodoName.text = it.approvalName
                binding.riskTodoTime.text = it.createTime
                binding.riskTodoLevel.text = when (it.eventLevel) {
                    "1" -> "高"
                    "2" -> "中"
                    else -> "低"
                }
                binding.riskTodoSch.text = it.relationName
                binding.riskTodoDes.text = it.riskDescription
                if (!it.annex.isNullOrEmpty()) {
                    binding.riskTodoAtts.text = it.annex[0].name
                }
            }
        }
        vm.judgmentForm.observe(this) {
            if (null != it) {
                binding.riskTodoCheckName.text = "${it.devOpsName} 审批"
                binding.riskTodoCheckTime.text = it.createTime
                binding.riskTodoCheckHint.text = it.remarks
            }
        }
        vm.managementForm.observe(this) {
            if (null != it) {
                binding.riskTodoTodoTime.text = it.createTime
                binding.riskTodoTodoHint.text = it.remarks
            }
        }

        LoadingDialog.showDialog("")
        vm.getRecordList(workNum!!)
    }


    lateinit var photoPath: String
    val REQUEST_IMAGE_CAPTURE = 10013

    private fun dispatchTakePictureIntent() {
        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
            // Ensure that there's a camera activity to handle the intent
            val c: ComponentName? = takePictureIntent.resolveActivity(packageManager)
            if (null == c) {
                "启动相机失败".showMessage()
            } else {
                val photoURI = FileHelper.getFileUri(
                    File.createTempFile(
                        TimeHelper.getTimeMillis().toString(),
                        ".jpg",
                        File(FileHelper.getImagePath())
                    ).also { photoPath = it.absolutePath }
                )

                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IMAGE_CAPTURE) {
            if (resultCode == RESULT_OK) {
                LoadingDialog.showDialog("")
                vm.annexManagementform(File(photoPath))
            }

        }
    }
}